<template>
  <div class="container">
    <el-card class="box-card">
      <template #header>
        <span>{{ showTitle }}</span>
      </template>
      <el-form
        class="demo-form-inline"
        :model="questionInfo"
        :rules="rules"
        ref="QuestionForm"
        style="padding: 0 30px"
      >
        <el-form-item label="学科：" prop="subjectID">
          <el-select
            placeholder="请选择"
            v-model="questionInfo.subjectID"
            @change="subjectChange"
          >
            <el-option
              v-for="item in subjectList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录：" prop="catalogID">
          <el-select placeholder="请选择" v-model="questionInfo.catalogID">
            <el-option
              v-for="item in catalogLis"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业：" prop="enterpriseID">
          <el-select placeholder="请选择" v-model="questionInfo.enterpriseID">
            <el-option
              v-for="item in companysList"
              :key="item.id"
              :label="item.shortName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市：" prop="province">
          <el-select
            placeholder="请选择"
            v-model="questionInfo.province"
            @change="getAllCity"
            style="width: 8.5%"
          >
            <el-option
              v-for="(item, index) in allProvince"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
          <el-select
            placeholder="请选择"
            style="margin-left: 20px; width: 8.5%"
            v-model="questionInfo.city"
          >
            <el-option
              v-for="(item, index) in allCity"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方向：" prop="direction">
          <el-select placeholder="请选择" v-model="questionInfo.direction">
            <el-option
              v-for="(item, index) in direction"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型：" prop="questionType">
          <el-radio-group
            v-model="questionInfo.questionType"
            @change="changeQuestionType(questionInfo.questionType)"
          >
            <el-radio
              v-for="item in questionType"
              :key="item.value"
              :label="String(item.value)"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度：" prop="difficulty">
          <el-radio-group v-model="questionInfo.difficulty">
            <el-radio
              v-for="item in difficulty"
              :key="item.value"
              :label="String(item.value)"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干：" prop="question">
          <WangEditor
            v-model="questionInfo.question"
            ref="question"
          ></WangEditor>
        </el-form-item>
        <!-- 单选 -->
        <el-form-item label="选项：" v-if="questionInfo.questionType === '1'">
          <div
            class="option"
            v-for="item in questionInfo.options"
            :key="item.code"
          >
            <el-radio
              v-model="item.isRight"
              :label="true"
              @change="clickRadio(item.code)"
              >{{ item.code }}</el-radio
            >
            <el-input
              placeholder="请输入内容"
              style="width: 200px"
              v-model="item.title"
            ></el-input>
            <image-upload :ref="item.code"></image-upload>
          </div>
          <el-button
            type="primary"
            style="margin-left: 75px; font-size: 12px"
            disabled
          >
            +增加选项与答案
          </el-button>
          <el-button
            type="danger"
            style="margin-left: 75px; font-size: 12px"
            disabled
          >
            -移除选项与答案
          </el-button>
        </el-form-item>
        <!-- 多选 -->
        <el-form-item label="选项：" v-if="questionInfo.questionType === '2'">
          <div
            class="option"
            v-for="item in questionInfo.options"
            :key="item.code"
          >
            <el-checkbox v-model="item.isRight">{{ item.code }}</el-checkbox>
            <el-input
              placeholder="请输入内容"
              style="width: 200px"
              v-model="item.title"
            ></el-input>
            <image-upload :ref="item.code"></image-upload>
          </div>
          <el-button
            type="primary"
            style="margin-left: 75px; font-size: 12px"
            @click="addOption"
          >
            +增加选项与答案
          </el-button>
          <el-button
            type="danger"
            style="margin-left: 75px; font-size: 12px"
            @click="removeOption"
          >
            -移除选项与答案
          </el-button>
        </el-form-item>
        <el-form-item label="解析视频：" style="width: 500px">
          <el-input
            style="width: 80%"
            v-model="questionInfo.videoURL"
          ></el-input>
        </el-form-item>
        <el-form-item label="答案解析：" prop="answer" ref="answer">
          <WangEditor v-model="questionInfo.answer"></WangEditor>
        </el-form-item>
        <el-form-item label="题目备注：">
          <el-input
            type="textarea"
            style="width: 30%"
            v-model="questionInfo.remarks"
          ></el-input>
        </el-form-item>
        <el-form-item label="试题标签 :">
          <el-select v-model="questionInfo.tags" multiple>
            <el-option
              v-for="item in tagList"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            style="margin-left: 70px"
            @click="confirmQuestion"
            v-if="questionID === ''"
          >
            确认提交
          </el-button>
          <el-button
            type="success"
            style="margin-left: 70px"
            @click="confirmQuestion"
            v-if="questionID !== ''"
          >
            确认修改
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 获取学科列表
import { simple as getSubjectListApi } from '@/api/hmmm/subjects'
// 获取公司列表
import { list as companysListApi } from '@/api/hmmm/companys'
// 获取目录
import { simple as getCatalogLisApi } from '@/api/hmmm/directorys'
// 城市获取
import { provinces, citys as getCity } from '@/api/hmmm/citys'
// 方向、问题类型、难度
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
// 标签列表
import { simple as getTagsListApi } from '@/api/hmmm/tags'
// 录入试题、试题详情、修改试题
import {
  add as addQuestionApi,
  detail as getQuestionDetailApi,
  update as editQuestionApi
} from '@/api/hmmm/questions'
// 选项枚举
import { options as optionList } from '@/api/hmmm/option'
export default {
  name: 'questions-new',
  components: {},
  // mounted () {
  //   console.log(this.questionInfo.test)
  // },
  data () {
    return {
      showTitle: '试题录入',
      questionInfo: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        options: [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ],
        videoURL: '',
        answer: '',
        remarks: '',
        tags: []
      },
      rules: {
        subjectID: [
          {
            required: true,
            message: '学科不能为空',
            trigger: ['blur', 'change']
          }
        ],
        catalogID: [
          {
            required: true,
            message: '目录不能为空',
            trigger: ['blur', 'change']
          }
        ],
        enterpriseID: [
          {
            required: true,
            message: '企业不能为空',
            trigger: ['blur', 'change']
          }
        ],
        province: [
          {
            required: true,
            message: '城市不能为空',
            trigger: ['blur', 'change']
          }
        ],
        city: [
          {
            required: true,
            message: '城市不能为空',
            trigger: ['blur', 'change']
          }
        ],
        direction: [
          {
            required: true,
            message: '方向不能为空',
            trigger: ['blur', 'change']
          }
        ],
        questionType: [
          {
            required: true,
            message: '类型不能为空',
            trigger: ['blur', 'change']
          }
        ],
        difficulty: [
          {
            required: true,
            message: '难度不能为空',
            trigger: ['blur', 'change']
          }
        ],
        question: [
          {
            required: true,
            message: '题干不能为空',
            trigger: ['blur', 'change']
          }
        ],
        answer: [
          {
            required: true,
            message: '答案解析不能为空',
            trigger: ['blur', 'change']
          }
        ]
      },
      // 学科列表
      subjectList: {},
      // 目录列表
      catalogLis: {},
      // 企业列表
      companysList: {},
      // 城市列表
      allProvince: [],
      allCity: [],
      // 方向列表
      direction,
      // 类型
      questionType,
      // 难度
      difficulty,
      // 标签列表
      tagList: [],
      // 单选框是否被选中
      // radioChecked: '',
      // 试题id
      questionID: ''
    }
  },
  created () {
    this.getSubjectList()
    this.getCompanysList()
    this.getAllProvince()
    this.questionID = this.$route.query.id || ''
    if (this.questionID !== '') {
      this.getQuestionDetail()
      this.showTitle = '试题修改'
    }
  },
  methods: {
    /**
     * 改变选项顺序
     * arr 目标数组
     * options 枚举数组
     */
    changeOptionOrder (arr, options) {
      const result = []
      options.forEach(obj => {
        const res = arr.find(item => {
          return item.code === obj.value
        })
        if (result.length === arr.length) return
        result.push(res)
      })
      return result
    },
    /**
     * 判断图片地址是否有效
     */
    checkImgExists (imgurl) {
      return new Promise(function (resolve, reject) {
        var ImgObj = new Image()
        ImgObj.src = imgurl
        ImgObj.onload = function (res) {
          resolve(res)
        }
        ImgObj.onerror = function (err) {
          reject(err)
        }
      })
    },
    /**
     * 获取试题详情
     */
    async getQuestionDetail () {
      const { data } = await getQuestionDetailApi({ id: this.questionID })
      // 修改isRight 类型
      data.options = data.options.map(item => {
        item.isRight = Boolean(item.isRight)
        return item
      })
      // 修改code顺序按照abcd
      data.options = this.changeOptionOrder(data.options, optionList)
      // 修改标签tags
      data.tags = data.tags?.length > 0 ? data.tags?.split(',') : ''
      // 回显图片
      data.options.forEach(async item => {
        const Ref = item.code
        if (item.img === '') return
        // 判断图片地址是否有效
        await this.checkImgExists(item.img).catch(() => {
          item.img =
            'https://seventeen-1314261668.cos.ap-beijing.myqcloud.com/1666259163409-1666259116685.jpg'
        })
        // console.log(this.$refs[Ref])
        this.$refs[Ref][0].fileList = [{ url: item.img }]
        // console.log(this.$refs[Ref][0].fileList)
      })
      this.questionInfo = { ...data }
    },
    /**
     * 移除选项
     */
    removeOption () {
      // 获取最后一个选项
      const last = this.questionInfo.options.slice(-1)[0]
      let { id } = optionList.find(item => item.value === last.code)
      --id
      const code = optionList.find(item => item.id === id)
      this.questionInfo.options.splice(code.id, 1)
      if (id === 1) return this.$message.warning('不能再少了')
    },
    /**
     * 增加选项
     */
    addOption () {
      const last = this.questionInfo.options.slice(-1)[0]
      let { id } = optionList.find(item => item.value === last.code)
      ++id
      const code = optionList.find(item => item.id === id)
      this.questionInfo.options.push({
        code: `${code.value}`,
        title: '',
        img: '',
        isRight: false
      })
      if (id === 13) return this.$message.warning('不能再多了')
    },
    /**
     * 确认提交
     */
    confirmQuestion () {
      this.$refs.QuestionForm.validate(async flag => {
        if (!flag) return
        this.questionInfo.options.forEach(item => {
          const Ref = item.code
          item.img = this.$refs[Ref][0]?.fileList[0]?.url || ''
        })
        this.questionInfo.tags = this.questionInfo.tags.join(',')
        // 修改
        if (this.questionID) {
          await editQuestionApi(this.questionInfo)
          this.$message.success('修改成功')
        } else {
          // 录入
          await addQuestionApi(this.questionInfo)
          this.$message.success('录入成功')
        }
        // 清空校验规则
        this.$refs.QuestionForm.resetFields()
        // 跳转
        this.$router.push('/questions/list')
      })
    },
    /**
     * 点击单选按钮
     */
    clickRadio (code) {
      this.questionInfo.options.forEach(item => {
        if (item.code !== code) item.isRight = false
      })
    },
    /**
     * 改变题型
     */
    changeQuestionType (value) {
      if (value === '3') {
        this.questionInfo.options = []
      } else {
        this.questionInfo.options = [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ]
      }
    },
    /**
     * 获取学科列表
     */
    async getSubjectList () {
      const { data } = await getSubjectListApi()
      // console.log(data)
      this.subjectList = data
    },
    /**
     * 学科改变获取目录 获取标签
     */
    async subjectChange () {
      const { data } = await getCatalogLisApi({
        subjectID: this.questionInfo.subjectID
      })
      this.catalogLis = data
      /**
       * 获取标签列表
       */
      const { data: tagTata } = await getTagsListApi({
        subjectID: this.questionInfo.subjectID
      })
      this.tagList = tagTata
      // 重置标签 目录内容
      this.questionInfo.catalogID = ''
      this.questionInfo.tags = []
    },
    /**
     * 获取公司列表
     */
    async getCompanysList () {
      const {
        data: { items }
      } = await companysListApi({ pagesize: 1000 })
      this.companysList = items
    },
    /**
     * 获取所有城市
     */
    getAllProvince () {
      const res = provinces()
      // console.log(res)
      this.allProvince = res
    },
    getAllCity () {
      const res = getCity(this.questionInfo.province)
      this.allCity = res
    }
  }
}
</script>

<style scoped lang='scss'>
.container {
  margin: 20px;
  ::v-deep .el-form-item__content {
    .option {
      display: flex;
      justify-content: space-around;
      width: 400px;
      margin-bottom: 10px;
      margin-left: 60px;
      .el-checkbox {
        line-height: 50px;
      }
      .el-radio {
        margin-top: 16px;
        margin-right: 0;
      }
      .el-input--medium {
        margin-top: 6px;
      }
      .image-upload {
        width: 70px;
        height: 50px;
        margin: 0, auto;
        .el-upload-list__item {
          transition: none !important;
        }
        .el-upload--picture-card {
          display: inline-block;
          position: relative;
          width: 70px;
          height: 50px;
        }
        .el-upload-list__item.is-success,
        .el-upload-list__item.is-uploading {
          width: 100%;
          height: 100%;
        }
        .el-progress-circle {
          height: 50px !important;
          width: 50px !important;
          transform: translateX(35px);
        }
        .el-upload-list__item.is-uploading.focusing.el-list-leave-active.el-list-leave-to {
          width: 100%;
          height: 100%;
        }
        .el-icon-plus {
          position: absolute;
          top: 20%;
          left: 30%;
        }
      }
    }
  }
}
</style>
